#!/usr/bin/env python
from __future__ import print_function
import numpy as np
from maputility2 import maptools
from XmlTools import SMKernel

def fixer(xmlfile, mapfile):
    m = maptools.mapOpen(mapfile, verbose=False)
    x = SMKernel.SourceModel(xmlfile, raiseErr=True)
    for sname, src in x.srcList.items():
        if not src.isfree:
            continue
        if (src.type == 'DiffuseSource') and \
                src.spatialModel.type in {'SpatialMap', 'MapCubeFunction', 'ConstantValue'}:
            print('[warn] please check the source {!r} yourself'.format(sname))
            continue
        ra, dec = float(src.spatialModel.RA.value), float(src.spatialModel.DEC.value)
        xpix, ypix = m.sky2pix(ra, dec, coord='CEL')
        if (not (0<=xpix<m.nxpix and 0<=ypix<m.nypix)):
            print('freeze {!r}'.format(sname))
            src.freeze()

    x.writeTo(xmlfile)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='freeze the sources outside the ROI')
    parser.add_argument('xmlfile', help='the input xmlfile')
    parser.add_argument('mapfile', help='the input mapfile')
    args = parser.parse_args()
    fixer(args.xmlfile, args.mapfile)